package com.colin.util.redisson;

import javax.annotation.Resource;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedissonUtil {

    @Resource
    private RedissonClient redissonClient;

    /**
     * redission分布锁实现demo
     *
     */
    public void lockTest() {

        // 获取锁
        RLock lock = redissonClient.getLock("111");

        try {

            // 尝试拿锁,100s后停止重试,返回false
            // 拿到锁后，10s后会自动释放
            boolean res2 = lock.tryLock(100, 10, TimeUnit.SECONDS);
            if (!res2) {
                // 100s都没获取到锁，可返回提示
            }

            // 继续执行业务逻辑

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            if (lock.isLocked()) {
                lock.unlock();
            }
        }

    }
}
